<script setup>
import { showToast } from 'vant'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { getUserClockStatusApi, userClockApi } from '@/apis/user'

const router = useRouter()

// 是否有奖品,打卡两个站点和四个站点时会有奖品
let prize = ref('')
let isAns = ref(false)
let dkNum = ref(0) // 完成打卡的站点数量

// 地图信息列表
let mapList = ref([
  {
    id: '9622895784',
    name: 'AI挥氧山水间',
    mimgurl: new URL('../assets/img/m1.png', import.meta.url),
    m_activeimgurl: new URL('../assets/img/m1_0.png', import.meta.url),
    bgimgurl: new URL('../assets/img/bg_t1.jpg', import.meta.url),
    dimgurl: new URL('../assets/img/d1.png', import.meta.url),
    successImg: new URL('../assets/img/d1_1.png', import.meta.url),
    isActive: false
  },
  {
    id: '5135684632',
    name: 'AI花绽-保鲜密码',
    mimgurl: new URL('../assets/img/m2.png', import.meta.url),
    m_activeimgurl: new URL('../assets/img/m2_0.png', import.meta.url),
    bgimgurl: new URL('../assets/img/bg_t2.jpg', import.meta.url),
    dimgurl: new URL('../assets/img/d2.png', import.meta.url),
    successImg: new URL('../assets/img/d2_1.png', import.meta.url),
    isActive: false
  },
  {
    id: '9333315769',
    name: 'AI画师',
    mimgurl: new URL('../assets/img/m3.png', import.meta.url),
    m_activeimgurl: new URL('../assets/img/m3_0.png', import.meta.url),
    bgimgurl: new URL('../assets/img/bg_t3.jpg', import.meta.url),
    dimgurl: new URL('../assets/img/d3.png', import.meta.url),
    successImg: new URL('../assets/img/d3_1.png', import.meta.url),
    isActive: false
  },
  {
    id: '9128376817',
    name: 'AI零度冰雪',
    mimgurl: new URL('../assets/img/m4.png', import.meta.url),
    m_activeimgurl: new URL('../assets/img/m4_0.png', import.meta.url),
    bgimgurl: new URL('../assets/img/bg_t4.jpg', import.meta.url),
    dimgurl: new URL('../assets/img/d4.png', import.meta.url),
    successImg: new URL('../assets/img/d4_1.png', import.meta.url),
    isActive: false
  }
])

// 获取用户打卡状态
const getUserStatus = async () => {
  dkNum.value = 0
  const res = await getUserClockStatusApi()
  if (res.data.code !== 200) {
    return showToast(res.data.msg)
  }
  let data = res.data.data
  if (data.s1 == 1) {
    mapList.value[0].isActive = true
    dkNum.value++
  } else {
    mapList.value[0].isActive = false
  }

  if (data.s2 == 1) {
    mapList.value[1].isActive = true
    dkNum.value++
  } else {
    mapList.value[1].isActive = false
  }

  if (data.s3 == 1) {
    mapList.value[2].isActive = true
    dkNum.value++
  } else {
    mapList.value[2].isActive = false
  }

  if (data.s4 == 1) {
    mapList.value[3].isActive = true
    dkNum.value++
  } else {
    mapList.value[3].isActive = false
  }
  data.q == 1 ? (isAns.value = true) : (isAns.value = false)
}

getUserStatus()

// 用户打卡
const userClock = async (id) => {
  const res = await userClockApi({ s: id.toString() })
  if (res.data.code !== 200) {
    return showToast(res.data.msg)
  }
  // 播放音效
  playAudio()
  // 奖品信息
  prize.value = res.data.data.prize
  // 更新状态
  getUserStatus()
}

// 打卡弹窗页
let showDetail = ref(false)
// 是否打卡成功标识
let isActiveFlag = ref(false)

// 地图上点的id
let mid = ref('')
// id对应的点的背景图和图标
let mbgimgurl = ref('')
// 未打卡之前的图标
let mdimgurl = ref('')
// 打卡成功图
let successImg = ref('')

// 拉起失败回调
const showFailed = () => {
  showToast('盖章页面拉起失败')
}

const audioRef = ref(null)

function playAudio() {
  if (audioRef.value) {
    audioRef.value.play().catch((error) => {
      console.error('Error playing audio:', error)
    })
  }
}

// 盖章成功
const showSuccess = (stampid) => {
  // 更新打卡点状态
  mapList.value.forEach((item, index) => {
    if (item.id === stampid) {
      userClock(index + 1)
    }
  })

  isActiveFlag.value = true
  // 移除关闭按钮
  document.getElementById('closeGzPage').remove()
  document.getElementById('testbtn').remove()

  let t = setTimeout(() => {
    // 关闭盖章页
    esp.closeStampCertifcationPage()
    showDetail.value = false
    clearTimeout(t)
    // 是否出奖品
    if (prize.value !== '') {
      router.replace({ path: '/lottery', query: { prize: prize.value, num: dkNum.value } })
    }
  }, 2000)
}

// 点击打卡点
const toDetail = (id) => {
  mid.value = id
  mapList.value.forEach((item) => {
    if (item.id === id) {
      if (item.isActive) {
        return showToast('该点位已打卡')
      }
      mbgimgurl.value = item.bgimgurl
      mdimgurl.value = item.dimgurl
      successImg.value = item.successImg
      // 拉起打卡页面
      isActiveFlag.value = false
      showDetail.value = true
      // 拉起盖章页面
      esp.showStampCertifcationPage(
        {
          licenseId: 'L29578574823', //联系管理员获取（必填）
          merchantCode: 'A29474683191', //联系管理员获取（必填）
          regionCode: esp.REGION_CODE_TYPE.CHINA,
          languageCode: esp.LANGUAGE_CODE_TYPE.CHINESE
        },
        showFailed
      )
      // 动态添加关闭按钮
      let btn = document.createElement('img')
      btn.src = new URL('../assets/img/btn_back.png', import.meta.url)
      btn.id = 'closeGzPage'
      btn.style.position = 'fixed'
      btn.style.left = 'calc(50% - 1.34rem)'
      btn.style.bottom = '1.73rem'
      btn.style.width = '2.68rem'
      btn.style.zIndex = '1002'
      document.body.appendChild(btn)
      // 影藏盖章页面关闭按钮
      document.getElementById('maopai-stamp-close-btn').style.display = 'none'
      btn.onclick = () => {
        btn.remove()
        document.getElementById('testbtn').remove()
        esp.closeStampCertifcationPage()
        showDetail.value = false
      }

      // 虚拟盖章按钮
      let tbtn = document.createElement('img')
      tbtn.src = new URL('../assets/img/btn_test.png', import.meta.url)
      tbtn.id = 'testbtn'
      tbtn.style.position = 'fixed'
      tbtn.style.opacity = '0'
      tbtn.style.right = '0'
      tbtn.style.top = '0'
      tbtn.style.width = '3.5rem'
      tbtn.style.zIndex = '1002'
      document.body.appendChild(tbtn)
      let cnum = ref(0)
      let ctimer = null
      tbtn.addEventListener('click', () => {
        cnum.value++
        // console.log(cnum.value)
        if (ctimer == null) {
          // 连续点击6次 打卡成功
          ctimer = setTimeout(() => {
            if (cnum.value >= 6) {
              // 盖章成功
              showSuccess(id)
            }
            cnum.value = 0
            clearTimeout(ctimer)
            ctimer = null
          }, 3000)
        }
      })
    }
  })
}

esp.onBeforeStamp(function cb(data) {
  //   console.log('盖章前回调', data)
})

//设置盖章认证失败回调
esp.certError(function cb(data) {
  //   alert('接受到认证失败回调:' + data.resMsg)
  showToast(data.resMsg)
})

// 不显示输入密码icon
esp.setNotShowOptIcon()

//设置盖章认证成功回调
esp.certSuccess(function cb(data) {
  // alert('接受到认证成功,该印章Id: [' + data.result.stamp + '] .')
  if (mid.value !== data.result.stamp) {
    return showToast('印章不匹配')
  }
  showSuccess(data.result.stamp)
})

//设置盖章页背景颜色（red, green, blue, opecity）
esp.setBackgroundColor(0, 0, 0, 0)

//设置盖章页文字 (传空则不显示)
esp.setDescription('')

//设置是否展示盖章动画
esp.setIconYn(false)

//设置是否隐藏盖章页
// esp.setHideStampLayer()

//代码关闭盖章页面
// esp.closeStampCertifcationPage()

// 去兑换
const toExchange = () => {
  if (dkNum.value >= 2) {
    isAns.value ? router.replace('/exchange') : router.replace('/questions')
  } else {
    showToast('请至少完成两个站点打卡')
  }
}
</script>
<template>
  <!-- 盖章成功音效 -->
  <audio controls="controls" ref="audioRef" preload hidden>
    <source src="../assets/media/stamp.mp3" type="audio/mp3" />
  </audio>
  <div class="map box bg clmcenter">
    <!-- <div class="pointbox p1">
      <div class="pitem clmcenter" @click="toDetail(mapList[0].id)">
        <p class="pname">{{ mapList[0].name }}</p>
        <img :src="mapList[0].mimgurl" class="pimg" />
      </div>
      <div class="pitem clmcenter" @click="toDetail(mapList[1].id)">
        <p class="pname">{{ mapList[1].name }}</p>
        <img :src="mapList[1].mimgurl" class="pimg" />
      </div>
    </div> -->
    <img src="@/assets/img/slogan.png" class="logo" />
    <div class="mapbox">
      <div
        :class="['mitem clmcenter', `mitem${index + 1}`]"
        v-for="(item, index) in mapList"
        :key="item.id"
      >
        <img
          :src="item.isActive ? item.m_activeimgurl : item.mimgurl"
          class="mimg"
          @click="toDetail(item.id)"
        />
        <p class="mname">{{ item.name }}</p>
      </div>
      <div class="mitem clmcenter mitem5" @click="toExchange">
        <img src="@/assets/img/m5_0.png" class="mimg mimg5" />
        <p class="mname">兑换处</p>
      </div>
    </div>
    <!-- <div class="pointbox p2">
      <div class="pitem clmcenter" @click="toDetail(mapList[2].id)">
        <img :src="mapList[2].mimgurl" class="pimg" />
        <p class="pname">{{ mapList[2].name }}</p>
      </div>
      <div class="pitem clmcenter" @click="toDetail(mapList[3].id)">
        <img :src="mapList[3].mimgurl" class="pimg" />
        <p class="pname">{{ mapList[3].name }}</p>
      </div>
      <div class="pitem clmcenter" @click="toExchange">
        <img src="@/assets/img/m5.png" class="pimg" />
        <p class="pname">兑换处</p>
      </div>
    </div> -->
    <img src="@/assets/img/btn_mine.png" class="btn btn_mine btnani" @click="toExchange" />
  </div>
  <div class="detail box bg clmcenter" v-show="showDetail">
    <img src="@/assets/img/slogan.png" class="logo" />
    <div class="dkbox clmcenter">
      <img :src="mbgimgurl" class="bgimg" />
      <img :src="mdimgurl" class="dimg btnani" v-if="!isActiveFlag" />
      <div class="sucbox" v-else>
        <img :src="successImg" class="dimg_active" />
        <p>打卡成功</p>
      </div>
    </div>
    <!-- <img src="@/assets/img/btn_back.png" class="btn btn_back" @click="closeDetail" /> -->
    <div class="maskbox" v-show="isActiveFlag"></div>
  </div>
</template>

<style lang="scss" scoped>
.logo {
  width: 311px;
}
.map {
  // .pointbox {
  //   width: 100%;
  //   display: flex;
  //   justify-content: space-evenly;
  //   align-items: center;
  //   .pitem {
  //     .pname {
  //       font-size: 25px;
  //       color: #ffffff;
  //     }
  //     .pimg {
  //       width: 88px;
  //     }
  //   }
  // }
  // .p1 {
  //   .pitem {
  //     .pimg {
  //       margin-top: 19px;
  //     }
  //   }
  // }
  // .p2 {
  //   margin-top: 40px;
  //   margin-bottom: 137px;
  //   .pitem {
  //     .pname {
  //       margin-top: 19px;
  //     }
  //   }
  // }

  .mapbox {
    margin-top: 97px;
    position: relative;
    width: 697px;
    height: 538px;
    background: url('@/assets/img/map.png') no-repeat;
    background-size: 100% 100%;
    .mitem {
      position: absolute;
      width: 102px;
      .mimg {
        width: 100%;
        animation: btnanito 1.5s linear infinite;
      }
      p {
        font-size: 25px;
        color: #ffffff;
        white-space: nowrap;
      }
    }
    .mitem1 {
      left: 150px;
      top: 80px;
    }
    .mitem2 {
      left: 404px;
      top: 68px;
    }
    .mitem3 {
      left: 50px;
      top: 388px;
    }
    .mitem4 {
      left: 305px;
      top: 210px;
    }
    .mitem5 {
      left: 475px;
      top: 344px;
    }
  }
  .btn_mine {
    margin-top: 268px;
  }
}
.detail {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1001;
  .dkbox {
    margin-top: 52px;
    margin-bottom: 120px;
    position: relative;
    width: 648px;
    height: 648px;
    background: url('@/assets/img/kuang.png') no-repeat;
    background-size: 100% 100%;
    .bgimg {
      position: absolute;
      width: 586px;
    }
    .dimg {
      width: 264px;
    }
    .sucbox {
      margin-top: 120px;
      z-index: 3;
      .dimg_active {
        width: 300px;
      }
      p {
        font-size: 40px;
        padding-top: 50px;
        text-align: center;
      }
    }
  }
  //   .btn_back {
  //     margin-top: 203px;
  //     position: fixed;
  //     bottom: 130px;
  //   }
  .maskbox {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
  }
}
</style>
